#!/usr/bin/python 
#   yongming.li

import re
import string
import os
import time
import  sys


from CPUChart import *
from Cpuinfo import *
from MemMonitor import *
from Myconfig import *
from ProMonitor import *
from CpuMonitor import *
from BatteryMonitor import *

import SocketServer

cpufilename='cpu.csv'

def writefile(name,buf,isreturn):

    f = file(name, 'a') # open for 'w'riting
    f.write(buf) # write text to file
    if isreturn != 0:
        f.write('\r\n' ) # write text to file
    f.close()
    return;

cpucontainer = []
memcontainer = []
memMonitor = MemMonitor()
cpuchart = CPUChart();
proMonitor = ProMonitor()
cpuMonitor =CpuMonitor()
batteryMonitor = BatteryMonitor()

#User 2%, System 4%, IOW 0%, IRQ 0%
#User 13 + Nice 0 + Sys 31 + Idle 579 + IOW 0 + IRQ 0 + SIRQ 0 = 623

def  parsecpu (s): 
    s=s.strip()

    if 'Nice' not in s:
        return -1 
    #print s
    cpuitem=string.split(s)

    cpuinfo = Cpuinfo(cpuitem[1],cpuitem[4],cpuitem[7],cpuitem[10],cpuitem[13],cpuitem[16],cpuitem[19],cpuitem[21]);

    #cpuinfo.dump();
    cpurate = cpuinfo.getCPUrate();
    #print cpurate

    
    if(cpurate < 100):
        cpuchart.showroundmeter('cpu',cpurate);
        if len(cpucontainer) > Myconfig.samplecount:
            del cpucontainer[0]    
        cpucontainer.append(cpurate);
        #print cpurate
        #print len(cpucontainer)
        cpuchart.showsimpleline('cpu',cpucontainer);
    return 0;


#   -n num  Updates to show before exiting.\n
#   -d num  Seconds to wait between updates.\n
def run(cmd,index):
        f = file('cpu.csv', 'w') # open for 'w'riting
        f.close()
        regsfile = os.popen(cmd).readlines()
        if regsfile:
           i = 0
           #print 'adb shell successful'
        else:
           print  'adb shell failed'
           sys.exit(0)

        for  line  in regsfile: 
            if len (line) == 0  or  len (line) <= 3:  # Zero length indicates EOF 
                continue  
            if index == 0:
                break
                if(parsecpu(line)==0):
                    break;
            if index == 1:
                    break;
            if index == 2:
                proMonitor.parse(line)
            if index ==3:
                cpuMonitor.parse(line)
                
        if index ==2:
            #cpuchart.showmultiline('process',ProMonitor.monitorcontainer);
            proMonitor.selectprosess()
            cpuchart.showmultiline('process',proMonitor);
        if index ==3:
            cpuchart.showmultiline('cpu',cpuMonitor);
        print  '-------------------------------------------------------------------------------'


cmds=[#'adb shell top -d 1 -n 1',
      'adb shell cat /proc/stat',
      'adb shell cat /proc/meminfo',
      'adb shell ps',
      'adb shell cat /proc/stat']
def takescreenshot():
    cmd = 'adb shell /system/bin/screencap  /data/xmeter.png'
    print cmd
    os.popen(cmd)
    cmd = 'adb pull  /data/xmeter.png  ./screencap/xmeter.png'
    print cmd
    os.popen(cmd)
     
def start():
    while True:
        cmdsize= len(cmds)
        for index in range(0,cmdsize):
            run(cmds[index],index);   
        batteryMonitor.start()
        memMonitor.start()
        #os.system('cp -rf ./out/ ./out_show')
        takescreenshot()
        time.sleep(1)
##############################################################################################################
class MyTCPHandler(SocketServer.BaseRequestHandler):
    """
    The RequestHandler class for our server.

    It is instantiated once per connection to the server, and must
    override the handle() method to implement communication to the
    client.
    """

    def handle(self):
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        print "{} wrote:".format(self.client_address[0])
        print self.data
        # just send back the same data, but upper-cased
        self.request.sendall(self.data.upper())
if __name__ == '__main__':
    HOST, PORT = "localhost", 4455
    # Create the server, binding to localhost on port 9999
    #server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    #server.serve_forever()

    start()

version =  '0.2'  


def cpumeterhelp():
    helpInfo = """
Build Environment Requirement
=============================================================
* ********* Suggested OS and Tool Chain to install *********
*
*       OS                         : Linux distribution Ubuntu 10.04
*       Memory Size                : 4G or above
*       make                       : GNU Make 3.81 or 3.82
*       python                     : Version 2.6.X
*       pyqt                       : 4.0
*       directchart                 :  ***
* **********************************************************
=============================================================

"""


